package com.lagou.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.common.Const;
import com.lagou.common.ResponseCode;
import com.lagou.common.ServerResponse;
import com.lagou.mapper.UserMapper;
import com.lagou.model.User;
import com.lagou.service.IUserService;
import com.lagou.util.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public ServerResponse<User> login(String username, String password) {

        //检查下用户名是否存在 (0 用户不存在，1用户存在)
        int resultCount = userMapper.checkUserName(username);

        if(resultCount <1){
            return ServerResponse.createByErrorMsg("用户名不存在");
        }

        //使用MD5给密码加密

        String md5Password = MD5Util.MD5EncodeUtf8(password);

        //调用mapper的登录方法，返回user对象
        User user = userMapper.selectLogin(username,md5Password);

        //如果user为null 则登录失败，密码错误

        if (user == null) {
            return ServerResponse.createByErrorMsg("密码错误");
        }

        //user不为null，登录成功，清空密码
        user.setPassword(StringUtils.EMPTY);

        //封装ServerResponse，返回成功信息

        return ServerResponse.createBySuccessMsgData("登录成功",user);
    }

    @Override
    public ServerResponse<PageInfo> getUsers(int pageNum, int pageSize) {

        PageHelper.startPage(pageNum,pageSize);

        List<User> list = userMapper.userList();

        PageInfo pageInfo = new PageInfo(list);

        return ServerResponse.createBySuccessData(pageInfo);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public ServerResponse<String> add(User user) {
        //校验用户名是否存在
        ServerResponse<String>  vilidResponse = this.checkValid(user.getUsername(), Const.USERNAME);

        if (vilidResponse.getStatus() != ResponseCode.SUCCESS.getCode()) {
            return vilidResponse;
        }

        //校验邮箱是否存在
        ServerResponse<String> checkValid = this.checkValid(user.getEmail(), Const.EMAIL);
        if (checkValid.getStatus() != ResponseCode.SUCCESS.getCode()) {
            return checkValid;
        }

        //使用MD5对密码进行加密

        user.setPassword(MD5Util.MD5EncodeUtf8(user.getPassword()));
        //添加数据入库

        int resultCount = userMapper.insert(user);

        if (resultCount == 0){
            return ServerResponse.createByErrorMsg("添加失败");
        }
        return ServerResponse.createBySuccessMsg("添加成功");
    }


    /**
     * 校验用户名和邮箱是否存在
     * @param str
     * @param type
     * @return
     */
    public ServerResponse<String> checkValid(String str,String type){

        if(StringUtils.isNotBlank(type)){

            if (Const.USERNAME.equals(type)) {
                //查询用户名是否存在
                int resultCount = userMapper.checkUserName(str);

                if (resultCount > 0) {
                    return ServerResponse.createByErrorMsg("用户名已存在");
                }
            }

            if (Const.EMAIL.equals(type)){

                int resultCount =  userMapper.checkEmail(str);
                if (resultCount > 0) {
                    return ServerResponse.createByErrorMsg("Email已存在");
                }
            }


        }
        return ServerResponse.createBySuccessMsg("校验成功");
    }


    /**
     * 删除用户方法
     * @param id
     * @return
     */
    @Override
    public ServerResponse<String> deleteByPrimary(int id) {


        //判断该用户是否存在，获取用户信息
        ServerResponse<User> information = this.getInformation(id);


        User user = information.getData();

        //如果不存在，返回失败信息
        if (user == null) {
            return ServerResponse.createByErrorMsg("删除的用户不存在");
        }

        int count = userMapper.deleteByPrimary(id);

        //如果用户存在，调用mapper中的删除方法，如果count为1，删除成功，count 为0，删除失败
        if (count  > 0) {
            return ServerResponse.createBySuccessMsg("删除成功");
        }else{
            return ServerResponse.createByErrorMsg("删除失败");
        }

    }


    /**
     * 根据ID获取用户信息
     * @param userId
     * @return
     */
    public ServerResponse<User> getInformation(int userId){

        User user =  userMapper.selectByPrimaryKey(userId);

      //根据ID查到了用户
        if (user != null) {
            return ServerResponse.createBySuccessData(user);
        }
        return ServerResponse.createByErrorMsg("用户不存在");
    }

    @Override
    public ServerResponse<String> update(User user) {


        User userOld =  userMapper.selectByPrimaryKey(user.getId());//根据用户ID查询原有用户信息

        //如果不是原有的用户名，才进行用户名的判断
        if(!userOld.getUsername().equals(user.getUsername())){
            //校验用户名是否存在
            ServerResponse<String>  vilidResponse = this.checkValid(user.getUsername(), Const.USERNAME);
            if (vilidResponse.getStatus() != ResponseCode.SUCCESS.getCode()) {
                return vilidResponse;
            }
        }

        //如果不是原有的邮箱，才进行用户名的判断
        if(!userOld.getEmail().equals(user.getEmail())){

            //校验邮箱是否存在
            ServerResponse<String> checkValid = this.checkValid(user.getEmail(), Const.EMAIL);
            if (checkValid.getStatus() != ResponseCode.SUCCESS.getCode()) {
                return checkValid;
            }
        }




        int resultCount = userMapper.update(user);

        if (resultCount == 0){
            return ServerResponse.createByErrorMsg("更新失败");
        }
        return ServerResponse.createBySuccessMsg("更新成功");

    }

}
